package org.yfl.mbg.enhance.utils;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.yfl.mbg.enhance.constants.CommonConstants;
import org.yfl.mbg.enhance.enums.OrmFrameworkEnum;
import org.yfl.mbg.enhance.exceptions.NotFoundOrmException;

import java.util.Date;

/**
 * @author yanfeilin
 * @version 1.0.0
 * @date 2020/5/24 11:07
 */
public class ClassUtil {

    private ClassUtil(){

    }

    /**
     * 判断classpath中存在某个类
     * @return
     */
    public static boolean isPresent(String classFullName){
        try {
            Class<?>  clazz= ClassUtils.getClass(classFullName);
            return clazz != null;
        }catch (ClassNotFoundException e){
            return false;
        }
    }

    /**
     * 推断orm框架
     * @return
     */
    public static OrmFrameworkEnum deduceOrmFramework(){
        if(isPresent(CommonConstants.JPA_FLAG_CLASS)){
            return OrmFrameworkEnum.JPA;
        }else if(isPresent(CommonConstants.MYBATIS_FLAG_CLASS)){
            return OrmFrameworkEnum.MYBATIS;
        }else {
            throw new NotFoundOrmException("未发现orm框架!");
        }
    }

    /**
     * 将pkg转换为文件路径
     * @param pkg
     * @return
     */
    public static String pkg2path(String pkg) {
        return pkg.replaceAll("\\.", "/");
    }

    /**
     * 生成java类的注释
     * @param description
     * @return
     */
    public static String getClassJavaDoc(String description){
        StringBuilder javaDocBuilder = new StringBuilder(256);
        /**
         * @author yanfeilin
         * @version 1.0.0
         * @date 2020/5/24 11:07
         */
        javaDocBuilder.append("/**").append(CommonConstants.LINE_SEPARATOR_WINDOWS)
                .append("* ").append(description).append(CommonConstants.LINE_SEPARATOR_WINDOWS)
                .append("* @author ").append(SystemUtils.USER_NAME).append(CommonConstants.LINE_SEPARATOR_WINDOWS)
                .append("* @date ").append(DateFormatUtils.format(new Date(),CommonConstants.DEFAULT_DATE_TIME_FORMAT))
                .append(CommonConstants.LINE_SEPARATOR_WINDOWS).append("*/");
        return javaDocBuilder.toString();
    }

    /**
     * java类字段新增注释
     * @param description
     * @return
     */
    public static String getClassFieldJavaDoc(String description){
        StringBuilder javaDocBuilder = new StringBuilder(128);

        javaDocBuilder.append("/**").append(description).append("*/");

        return javaDocBuilder.toString();
    }
}
